#!/bin/bash

# 定义颜色变量
red='\033[0;31m'
green='\033[0;32m'
yellow='\033[0;33m'
plain='\033[0m'

# 基本日志函数
function LOGE() {
    echo -e "${red}[错误] $* ${plain}"
}

function LOGI() {
    echo -e "${green}[信息] $* ${plain}"
}

# 检查是否已安装
check_install() {
    if [[ ! -f /etc/systemd/system/x-ui.service ]]; then
        LOGE "x-ui 未安装！"
        return 1
    fi
    return 0
}

# 检查是否未安装
check_uninstall() {
    if [[ -f /etc/systemd/system/x-ui.service ]]; then
        LOGE "x-ui 已经安装！"
        return 1
    fi
    return 0
}

# 显示使用方法
show_usage() {
    echo "x-ui 管理脚本使用方法: "
    echo "------------------------------------------"
    echo "x-ui              - 显示管理菜单"
    echo "x-ui start        - 启动 x-ui 面板"
    echo "x-ui stop         - 停止 x-ui 面板"
    echo "x-ui restart      - 重启 x-ui 面板"
    echo "x-ui status       - 查看 x-ui 状态"
    echo "x-ui enable       - 设置 x-ui 开机自启"
    echo "x-ui disable      - 取消 x-ui 开机自启"
    echo "x-ui log          - 查看 x-ui 日志"
    echo "x-ui update       - 更新 x-ui 面板"
    echo "x-ui install      - 安装 x-ui 面板"
    echo "x-ui uninstall    - 卸载 x-ui 面板"
    echo "------------------------------------------"
}

# 检查root权限
[[ $EUID -ne 0 ]] && LOGE "错误: 请使用root用户运行此脚本！" && exit 1

# 检查系统类型
if [[ -f /etc/os-release ]]; then
    source /etc/os-release
    release=$ID
elif [[ -f /usr/lib/os-release ]]; then
    source /usr/lib/os-release
    release=$ID
else
    echo "无法检测系统类型，请联系作者！" >&2
    exit 1
fi
echo "系统类型: $release"

# 确认操作
confirm() {
    if [[ $# > 1 ]]; then
        echo && read -rp "$1 [默认$2]: " temp
        if [[ "${temp}" == "" ]]; then
            temp=$2
        fi
    else
        read -rp "$1 [y/n]: " temp
    fi
    if [[ "${temp}" == "y" || "${temp}" == "Y" ]]; then
        return 0
    else
        return 1
    fi
}

# 安装x-ui面板
install() {
    bash <(curl -Ls https://raw.gitcode.com/meu/3x-ui/raw/main/install.sh)
    if [[ $? == 0 ]]; then
        if [[ $# == 0 ]]; then
            start
        else
            start 0
        fi
    fi
}

# 更新x-ui面板
update() {
    confirm "此操作将强制重新安装最新版本，数据不会丢失，是否继续?" "y"
    if [[ $? != 0 ]]; then
        LOGE "已取消"
        if [[ $# == 0 ]]; then
            before_show_menu
        fi
        return 0
    fi
    bash <(curl -Ls https://raw.gitcode.com/meu/3x-ui/raw/main/install.sh)
    if [[ $? == 0 ]]; then
        LOGI "更新完成，已自动重启面板"
        before_show_menu
    fi
}

# 卸载x-ui面板
uninstall() {
    confirm "确定要卸载面板吗，xray也会卸载?" "n"
    if [[ $? != 0 ]]; then
        if [[ $# == 0 ]]; then
            show_menu
        fi
        return 0
    fi
    systemctl stop x-ui
    systemctl disable x-ui
    rm /etc/systemd/system/x-ui.service -f
    systemctl daemon-reload
    systemctl reset-failed
    rm /etc/x-ui/ -rf
    rm /usr/local/x-ui/ -rf

    echo ""
    echo -e "卸载成功，如果要重新安装请使用以下命令:"
    echo -e "${green}bash <(curl -Ls https://raw.gitcode.com/meu/3x-ui/raw/main/install.sh)${plain}"
    echo ""
    rm "$0"
    exit 0
}

# 重置用户名和密码
reset_user() {
    confirm "确定要重置面板登录用户名和密码吗?" "n"
    if [[ $? != 0 ]]; then
        if [[ $# == 0 ]]; then
            show_menu
        fi
        return 0
    fi
    
    read -rp "请设置登录用户名 [默认随机生成]: " config_account
    [[ -z $config_account ]] && config_account=$(date +%s%N | md5sum | cut -c 1-8)
    read -rp "请设置登录密码 [默认随机生成]: " config_password
    [[ -z $config_password ]] && config_password=$(date +%s%N | md5sum | cut -c 1-8)

    /usr/local/x-ui/x-ui setting -username ${config_account} -password ${config_password}
    echo -e "面板登录用户名已重置为: ${green} ${config_account} ${plain}"
    echo -e "面板登录密码已重置为: ${green} ${config_password} ${plain}"
    restart
}

# 重置面板设置
reset_config() {
    confirm "确定要重置所有面板设置吗，账号数据不会丢失，用户名和密码不会改变" "n"
    if [[ $? != 0 ]]; then
        if [[ $# == 0 ]]; then
            show_menu
        fi
        return 0
    fi
    /usr/local/x-ui/x-ui setting -reset
    echo -e "所有面板设置已重置为默认值，现在请重启面板"
    restart
}

# 设置面板端口
set_port() {
    echo -n "请输入端口号[1-65535]: "
    read -r port
    if [[ -z "${port}" ]]; then
        echo "已取消"
        before_show_menu
    else
        /usr/local/x-ui/x-ui setting -port ${port}
        echo -e "端口已设置，现在请重启面板并使用新端口 ${green}${port}${plain} 访问面板"
        restart
    fi
}

# 检查面板状态
check_status() {
    if [[ ! -f /etc/systemd/system/x-ui.service ]]; then
        return 2
    fi
    temp=$(systemctl status x-ui | grep Active | awk '{print $3}' | cut -d "(" -f2 | cut -d ")" -f1)
    if [[ "${temp}" == "running" ]]; then
        return 0
    else
        return 1
    fi
}

# 启动面板
start() {
    check_status
    if [[ $? == 0 ]]; then
        echo ""
        LOGI "面板已运行，无需再次启动，如需重启请选择重启"
    else
        systemctl start x-ui
        sleep 2
        check_status
        if [[ $? == 0 ]]; then
            LOGI "x-ui 启动成功"
        else
            LOGE "面板启动失败，可能是因为启动时间超过了两秒，请稍后查看日志信息"
        fi
    fi
    if [[ $# == 0 ]]; then
        before_show_menu
    fi
}

# 停止面板
stop() {
    check_status
    if [[ $? == 1 ]]; then
        echo ""
        LOGI "面板已停止，无需再次停止"
    else
        systemctl stop x-ui
        sleep 2
        check_status
        if [[ $? == 1 ]]; then
            LOGI "x-ui 与 xray 停止成功"
        else
            LOGE "面板停止失败，可能是因为停止时间超过了两秒，请稍后查看日志信息"
        fi
    fi
    if [[ $# == 0 ]]; then
        before_show_menu
    fi
}

# 重启面板
restart() {
    systemctl restart x-ui
    sleep 2
    check_status
    if [[ $? == 0 ]]; then
        LOGI "x-ui 与 xray 重启成功"
    else
        LOGE "面板重启失败，可能是因为启动时间超过了两秒，请稍后查看日志信息"
    fi
    if [[ $# == 0 ]]; then
        before_show_menu
    fi
}

# 查看日志
show_log() {
    journalctl -u x-ui.service -e --no-pager -f
}

# 设置开机自启
enable() {
    systemctl enable x-ui
    if [[ $? == 0 ]]; then
        LOGI "x-ui 已设置开机自启"
    else
        LOGE "x-ui 设置开机自启失败"
    fi
    
    if [[ $# == 0 ]]; then
        before_show_menu
    fi
}

# 取消开机自启
disable() {
    systemctl disable x-ui
    if [[ $? == 0 ]]; then
        LOGI "x-ui 已取消开机自启"
    else
        LOGE "x-ui 取消开机自启失败"
    fi
    
    if [[ $# == 0 ]]; then
        before_show_menu
    fi
}

# 显示菜单前的操作
before_show_menu() {
    echo && echo -n -e "${yellow}按回车返回主菜单: ${plain}" && read temp
    show_menu
}

# 显示面板状态
show_status() {
    check_status
    case $? in
        0)
            echo -e "面板状态: ${green}已运行${plain}"
            show_enable_status
            ;;
        1)
            echo -e "面板状态: ${yellow}未运行${plain}"
            show_enable_status
            ;;
        2)
            echo -e "面板状态: ${red}未安装${plain}"
            ;;
    esac
}

# 显示自启状态
show_enable_status() {
    check_enabled
    if [[ $? == 0 ]]; then
        echo -e "是否开机自启: ${green}是${plain}"
    else
        echo -e "是否开机自启: ${red}否${plain}"
    fi
}

# 检查是否已启用
check_enabled() {
    temp=$(systemctl is-enabled x-ui)
    if [[ "${temp}" == "enabled" ]]; then
        return 0
    else
        return 1
    fi
}

# 显示主菜单
show_menu() {
    echo -e "
  ${green}x-ui 面板管理脚本${plain}

  ${green}0.${plain} 退出脚本
————————————————————————————————
  ${green}1.${plain} 安装 x-ui
  ${green}2.${plain} 更新 x-ui
  ${green}3.${plain} 卸载 x-ui
————————————————————————————————
  ${green}4.${plain} 重置用户名密码
  ${green}5.${plain} 重置面板设置
  ${green}6.${plain} 设置面板端口
————————————————————————————————
  ${green}7.${plain} 启动 x-ui
  ${green}8.${plain} 停止 x-ui
  ${green}9.${plain} 重启 x-ui
 ${green}10.${plain} 查看 x-ui 日志
————————————————————————————————
 ${green}11.${plain} 设置开机自启
 ${green}12.${plain} 取消开机自启
 "
    show_status
    echo && read -p "请输入选择 [0-12]: " num

    case "${num}" in
        0) exit 0 ;;
        1) install ;;
        2) update ;;
        3) uninstall ;;
        4) reset_user ;;
        5) reset_config ;;
        6) set_port ;;
        7) start ;;
        8) stop ;;
        9) restart ;;
        10) show_log ;;
        11) enable ;;
        12) disable ;;
        *) echo -e "${red}请输入正确的数字 [0-12]${plain}" ;;
    esac
}

# 添加status函数
status() {
    systemctl status x-ui
    if [[ $# == 0 ]]; then
        before_show_menu
    fi
}

# 根据输入的参数执行相应的操作
if [[ $# > 0 ]]; then
    case $1 in
        "start") check_install 0 && start 0 ;;
        "stop") check_install 0 && stop 0 ;;
        "restart") check_install 0 && restart 0 ;;
        "status") check_install 0 && status 0 ;;
        "enable") check_install 0 && enable 0 ;;
        "disable") check_install 0 && disable 0 ;;
        "log") check_install 0 && show_log 0 ;;
        "update") check_install 0 && update 0 ;;
        "install") check_uninstall 0 && install 0 ;;
        "uninstall") check_install 0 && uninstall 0 ;;
        *) show_usage ;;
    esac
else
    show_menu
fi
